package com.jikangjun.disk.login.control;

import com.jikangjun.disk.common.Result;
import com.jikangjun.disk.email.EmailService;
import com.jikangjun.disk.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/findPassword")
public class FindPasswordControl {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private HttpSession httpSession;

    // 跳转找回密码页面
    @RequestMapping("/page")
    public String findPasswordPage() {
        return "login/findPasswordPage"; // 对应 templates/login/findPasswordPage.html
    }

    // 发送验证码
    @GetMapping("/sendCode")
    @ResponseBody
    public Result sendCode(@RequestParam String email) {
        boolean sendSuccess = emailService.sendCode(email, "find_");
        return new Result(sendSuccess,
                sendSuccess ? "Verification code sent to your email" : "Failed to send verification code");
    }

    // 验证验证码
    @PostMapping("/verifyCode")
    @ResponseBody
    public Result verifyCode(@RequestParam String email, @RequestParam String code) {
        boolean verifySuccess = emailService.verifyCode(email, code, "find_");
        return new Result(verifySuccess,
                verifySuccess ? "Verification code is valid" : "Invalid or expired verification code");
    }

    // 重置密码
    @PostMapping("/reset")
    @ResponseBody
    public Result resetPassword(@RequestParam String email, @RequestParam String newPassword) {
        if (!userService.checkEmailExists(email)) {
            return new Result(false, "Email not registered");
        }
        String encryptedPassword = userService.encryptPassword(newPassword);
        boolean updateSuccess = userService.updatePasswordByEmail(email, encryptedPassword);
        return new Result(updateSuccess,
                updateSuccess ? "Password reset successful" : "Failed to reset password");
    }
}